package com.py.chat.server.businese;

import com.py.chat.proto.IBusineseHandle;
import com.py.chat.server.ChatServer;
import com.py.chat.service.ChatLogService;
import com.py.chat.service.UserService;
import com.py.chat.utils.DrawExpUtil;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

import com.google.protobuf.MessageLite;
import com.py.chat.bean.ChatLog;
import com.py.chat.bean.Gloable;
import com.py.chat.bean.User;
import com.py.chat.dao.ChatLogDao;
import com.py.chat.dao.UserDao;
import com.py.chat.proto.ChatProbuf;
import com.py.chat.proto.ChatProbuf.CTSChat;
import com.py.chat.proto.ChatProbuf.CTSRegist;
import com.py.chat.proto.ChatProbuf.STCChatRet;



public class ServerChatHandle extends IBusineseHandle<CTSChat>{

	@Override
	public MessageLite handle(CTSChat msg) {
		String message = msg.getMsg();
		STCChatRet.Builder builder = STCChatRet.newBuilder();
		// 需要判断是用户是否登陆  是否可发送信息   
		if(session.user != null){
			// CD 判断是否可发送信息
			long sendMsgTime = System.currentTimeMillis();
			if(UserService.checkCD(session.user.getId(),sendMsgTime)){
				// 获得经验
				int exp = DrawExpUtil.getExp();
				// 加经验 
				UserService.addExp(session.user, exp);
				ChatLog chatLog = new ChatLog();
				chatLog.setId(UUID.randomUUID().toString());
				chatLog.setMsg(message);
				chatLog.setUser(session.user);
				chatLog.setCreateDate(sendMsgTime);
				// 新增聊天记录 将聊天记录放在内存 同时放在数据库中  
				ChatLogService.addChatLog(chatLog);
				builder.setStatus(0);
				builder.setMsg("发送成功");
				// 群发消息
				ChatServer.broadcast(STCChatRet.newBuilder().
						setStatus(1).setChatLog(ChatProbuf.ChatLog.newBuilder().
								setSendUserLevel(session.user.getLevel()).
								setSendUserName(session.user.getName()).
								setCreateDate(sendMsgTime).
								setMsg(message).build()).
						build()
						, session.user);
			}else{
				builder.setStatus(0);  
				builder.setMsg("CD未冷却");
			}
		}else{
			// 未登录
			builder.setStatus(0);  
			builder.setMsg("请先登陆");
		}
		return builder.build();
	}
	public static void main(String[] args) {
		System.err.println(Math.random());
	}
}
